﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using GatherWebLib;
using GatherWebLib.Model;
using System.Reflection;
using Novel.Entity;
using System.Net;
using Novel.BizLogic;
using GatherWebLib.publish;

namespace WebGet_Win
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private cGatherTask AddRunTask(string tClassName, string tName)
        {
            cTaskRun tr = new cTaskRun();
            cTaskClass tc = new cTaskClass();//任务分类
            string tPath = "";

            if (tClassName == "")
            {
                tPath = cXmlSConfig.TaskPath + "tasks";
            }
            else
            {
                tPath = tc.GetTaskClassPathByName(tClassName);
            }
            return null;
        }

        private void button1_Click(object sender, EventArgs e)
        {

           
          
        }



        //写日志事件
        private void tGather_Log(object sender, cGatherTaskLogArgs e)
        {
            //写日志
            string TaskName = e.TaskName;
            string strLog = e.strLog;
         

            try
            {
                InvokeMethod(this, "ShowInfo", new object[] { e.TaskName, strLog });

            }
            catch (System.Exception ex)
            {
                InvokeMethod(this, "ExportLog", new object[] { DateTime.Now + "：" + ex.Message });
            }

        }
        public void ShowInfo(string Title, string Info)
        {

            ExportLog(DateTime.Now + "：" + "<" + Title + ">    " + Info);

        }
        public void ExportLog(string str)
        {


           
                try
                {
                    cSystemLog sl = new cSystemLog();
                    sl.WriteLog(str);
                    sl = null;
                }
                catch (System.Exception ex)
                {
                    InvokeMethod(this, "ExportLog", new object[] { ex.Message });
                }
            
        }

        #region 委托代理

        delegate object invokemethod(object Instance, string Method, object[] parameters);

        /// <summary>
        /// 委托执行实例的方法，方法必须都是Public 否则会出错
        /// </summary>
        /// <param name="Instance">类实例</param>
        /// <param name="Method">方法名</param>
        /// <param name="parameters">参数列表</param>
        /// <returns>返回值</returns>
        private object InvokeMethod(object Instance, string Method, object[] parameters)
        {
            if ((bool)GetPropertyValue(Instance, "InvokeRequired"))
            {
                invokemethod d = new invokemethod(InvokeMethod);
                return this.Invoke(d, new object[] { Instance, Method, parameters });
            }
            else
            {
                return MethodInvoke(Instance, Method, parameters);
            }
        }
        /// <summary>
        /// 执行实例的方法
        /// </summary>
        /// <param name="ClassInstance">类实例</param>
        /// <param name="MethodName">方法名</param>
        /// <param name="parameters">参数列表</param>
        /// <returns>返回值</returns>
        private static object MethodInvoke(object ClassInstance, string MethodName, object[] parameters)
        {
            if (parameters == null)
            {
                parameters = new object[0];
            }
            Type myType = ClassInstance.GetType();
            Type[] types = new Type[parameters.Length];
            for (int i = 0; i < parameters.Length; ++i)
            {
                types[i] = parameters[i].GetType();
            }
            MethodInfo myMethodInfo = myType.GetMethod(MethodName, types);
            return myMethodInfo.Invoke(ClassInstance, parameters);
        }
        /// <summary>
        /// 获取实例的属性值
        /// </summary>
        /// <param name="ClassInstance">类实例</param>
        /// <param name="PropertyName">属性名</param>
        /// <returns>属性值</returns>
        private static object GetPropertyValue(object ClassInstance, string PropertyName)
        {
            Type myType = ClassInstance.GetType();
            PropertyInfo myPropertyInfo = myType.GetProperty(PropertyName, BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
            return myPropertyInfo.GetValue(ClassInstance, null);
        }
        #endregion

        private void btn_run_Click(object sender, EventArgs e)
        {


            try
            {



                cGatherTask Gather = new cGatherTask(GetTaskInfo());

                Gather.Log += tGather_Log;
               
                DataTable dt = Gather.Start();
                if (dt != null && dt.Rows.Count > 0)
                {
                    foreach (DataRow dr in dt.Rows)
                    {
                        int ID = int.Parse(dr["编号"].ToString());
                        T_004NovelBLLSub bll = new T_004NovelBLLSub();
                        NovelEntity novel = bll.GetNovelByID(ID);
                        if (novel == null)
                        {
                            T_004NovelEntity model = new T_004NovelEntity();
                            model.BookName = dr["书名"].ToString().Trim();
                            T_003Novel_TypesBLLSub type = new T_003Novel_TypesBLLSub();
                            int mainID = 0;
                            int subID = 0;
                            string chapterTableName = "";
                            type.GetIDAndTableNameByName(dr["sub类型"].ToString(), out mainID, out subID, out chapterTableName);
                            model.BookTypeID = subID;
                            model.BookTypeMainID = mainID;
                            model.TableName = chapterTableName;
                            model.BookNo = "";
                            model.CmfuID = ID;
                            model.CmfuInfoUrl = cTool.GetCompleteUrl(dr["地址"].ToString(), "http://www.qidian.com/");
                            model.CmfuListUrl = model.CmfuInfoUrl.Replace("/Book/", "/BookReader/");

                            int bookID = bll.Save(model);

                            UpdateNovelInfo(bookID, model.CmfuInfoUrl, model.CmfuListUrl);

                            GetNovelChapter(model.BookName, bookID, model.TableName);
                        }
                        else
                        {
                            UpdateNovelHit(novel.BookID, novel.CmfuInfoUrl, novel.CmfuListUrl);
                            int taskID = novel.LastTaskID;
                            if (taskID == 0)
                            {

                            }
                        }
                    }

                }
            }
            catch (Exception)
            {

                throw;
            }
        }
        DataTable tianyi = null;

        private void GetNovelChapter(string bookName, int bookID, string tableName)
        {
            string Url="";
            if (tianyi == null)
            {
                cTask_m task = GetTaskInfo();
                 Url= task.WebpageLink[0].Weblink;
                cGatherTask Gather = new cGatherTask(task);
                Gather.Log += tGather_Log;
                DataTable dt = Gather.Start();
            }

            if (tianyi!=null)
            {
                DataRow[] drs = tianyi.Select(string.Format("名称='{0}'", bookName));

                if (drs != null && drs.Length > 0)
                {
                    string url = cTool.GetCompleteUrl(drs[0]["地址"].ToString(), Url);
                    GetNovelChapterList(url, bookID,tableName);
                }
                else
                {
                    ExportLog("未找到，书名：" + bookName);
                }
            }


        }

        private void Publish(int taskID)
        {
            cPublishTask publish = new cPublishTask();

            publish.PublishCompleted += this.Publish_Complete;
            publish.PublishError += this.Publish_Error;

            publish.PublishStarted += this.Publish_Started;

            publish.PublishLog += this.Publish_Log;
            publish.m_pTaskData = GetPublishTask(taskID);
            publish.startPublic();
            
        }

        private cPublishTask_m GetPublishTask(int taskID)
        {
            cPublishTask_m task = new cPublishTask_m();
            return task;
        }



        private void GetNovelChapterList(string listUrl, int bookID, string tableName)
        {
            cTask_m task = GetTaskInfo();
            task.WebpageLink[0].Weblink = listUrl;
            cGatherTask Gather = new cGatherTask(task);
            Gather.Log += tGather_Log;
            DataTable dt = Gather.Start();

            if (dt != null && dt.Rows.Count > 0)
            {
                foreach (DataRow dr in dt.Rows)
                {
                    string url = cTool.GetCompleteUrl(dr["地址"].ToString(), listUrl);
                    string title = dr["章节名"].ToString();
                    GetNovelChapterContent(url, title, bookID, tableName);
                }
            }
        }

        private void GetNovelChapterContent(string contentUrl,string Title,int bookID,string tableName)
        {
            cTask_m task = GetTaskInfo();
            task.WebpageLink[0].Weblink = contentUrl;
            cGatherTask Gather = new cGatherTask(task);
            Gather.Log += tGather_Log;
            DataTable dt = Gather.Start();

            if (dt != null && dt.Rows.Count > 0)
            {
                Novel_ChapterEntity Chapter = new Novel_ChapterEntity();


                Novel_ChapterBLLSub bll = new Novel_ChapterBLLSub();
                bll.TableName = tableName;
                Chapter.BookID = bookID;
                Chapter.ChapterTitle = Title;
                Chapter.ChapterContent = dt.Rows[0]["内容"].ToString();
                bll.Save(Chapter);
            }
           
        }


        private void UpdateNovelInfo(int bookID,string infoUrl,string listUrl)
        {
            DataTable dt = GetCmfuNovelInfo(infoUrl);
            if(dt!=null&&dt.Rows.Count>0)
            {
                UpdateNovelIntro(dt.Rows[0], bookID);
                UpdateNovelCount(dt.Rows[0], bookID, listUrl);
            }
        }

        private DataTable GetCmfuNovelInfo(string infoUrl)
        {
            cTask_m task = GetTaskInfo();
            task.WebpageLink[0].Weblink = infoUrl;
            cGatherTask Gather = new cGatherTask(task);

            Gather.Log += tGather_Log;
            DataTable dt = Gather.Start();
            return dt;
        }

        private void UpdateNovelHit(int bookID, string infoUrl, string listUrl)
        {
            DataTable dt = GetCmfuNovelInfo(infoUrl);
            if (dt != null && dt.Rows.Count > 0)
            {
                UpdateNovelCount(dt.Rows[0], bookID, listUrl);
            }
        }

        /// <summary>
        /// 更新小说详情介绍
        /// </summary>
        /// <param name="dr"></param>
        /// <param name="bookID"></param>
        private void UpdateNovelIntro(DataRow dr,int bookID)
        {
            T_004NovelBLLSub bll = new T_004NovelBLLSub();

            T_004NovelEntity novel = new T_004NovelEntity();
            novel.BookID = bookID;
            novel.intro = dr["简介"].ToString();
            novel.Tags = dr["标签"].ToString();
            novel.author = dr["小说作者"].ToString();
            novel.Status = bll.GetWriteStatus(dr["写作进程"].ToString());
            bll.UpdateIntro(novel);
        }

        private void UpdateNovelCount(DataRow dr, int bookID, string listUrl)
        {
            T_005NovelInfoEntity NovelInfo = new T_005NovelInfoEntity();
            NovelInfo.BookID = bookID;
            NovelInfo.Hits = int.Parse(dr["总点击"].ToString());
            NovelInfo.MonthHits = int.Parse(dr["月点击"].ToString());
            NovelInfo.WeekHits = int.Parse(dr["周点击"].ToString());
            NovelInfo.Recommend = int.Parse(dr["总推荐"].ToString());
            NovelInfo.MonthRecommend = int.Parse(dr["月推荐"].ToString());
            NovelInfo.WeekRecommend = int.Parse(dr["周推荐"].ToString());
            NovelInfo.Length = int.Parse(dr["完成字数"].ToString());
            NovelInfo.CmfuChapterCount = GetNovelChapterCount(listUrl);
            T_005NovelInfoBLLSub bll = new T_005NovelInfoBLLSub();
            bll.UpdateHitCount(NovelInfo);
        }

        private int GetNovelChapterCount(string listUrl)
        {
            cTask_m task = GetTaskInfo();
            task.WebpageLink[0].Weblink = listUrl;
            cGatherTask Gather = new cGatherTask(task);
            Gather.Log += tGather_Log;
            DataTable dt = Gather.Start();
            if (dt != null)
            {
                return dt.Rows.Count;
            }
            return 0;
        }



        private void GetChapter(string BookName, string ChapterUrl,int taskID)
        { 
        
        }



        private cTask_m GetTaskInfo()
        {
            cTask task = new cTask();
           
            cTask_m m = task.GetTaskInfo(1);
            return m;
        }

        #region 发布任务的事件处理
        private void Publish_Complete(object sender, PublishCompletedEventArgs e)
        {
            InvokeMethod(this, "ShowInfo", new object[] { e.TaskName, "任务成功发布" });

           
        }
       
        private void Publish_Started(object sender, PublishStartedEventArgs e)
        {
            InvokeMethod(this, "ShowInfo", new object[] { e.TaskName, "任务开始进行数据发布" });


        }

        private void Publish_Error(object sender, PublishErrorEventArgs e)
        {
           
            InvokeMethod(this, "ShowInfo", new object[] { e.TaskName, "任务成功失败" });



        }

        private void Publish_Failed(object sender, PublishFailedEventArgs e)
        {
         
            InvokeMethod(this, "ShowInfo", new object[] { e.TaskName, "任务成功失败" });


        }

     

        private void Publish_Log(object sender, PublishLogEventArgs e)
        {
            //写发布任务的日志
            Int64 TaskID = e.TaskID;
            string strLog = e.strLog;
            string conName = "sCon" + TaskID;
            string pageName = "page" + TaskID;
        }

        #endregion
      
    }
}
